package com.example.esquel_carpool.ui.detail;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.blankj.utilcode.util.KeyboardUtils;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.esquel_carpool.R;
import com.example.esquel_carpool.utils.UrlImageHolderView;
import com.example.esquel_carpool.data.DetailListData;
import com.example.esquel_carpool.entity.detail.ChildCommentsBean;
import com.example.esquel_carpool.entity.detail.DataBean;
import com.example.esquel_carpool.entity.detail.DetailData;
import com.example.esquel_carpool.entity.detail.DetailListBean;

import com.example.esquel_carpool.entity.home.ImagesBean;
import com.example.esquel_carpool.entity.home.ListBean;
import com.example.esquel_carpool.entity.home.StatisticalBean;
import com.example.esquel_carpool.entity.home.UserBean;
import com.example.esquel_carpool.glideModule.GlideApp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class DetailActivity extends AppCompatActivity implements View.OnClickListener, KeyboardUtils.OnSoftInputChangedListener {

    public static void entry(Context from, ListBean item) {
        Intent intent = new Intent(from, DetailActivity.class);
        intent.putExtra("data", item);
        from.startActivity(intent);
    }

    private Toolbar toolbar2;

    private ConvenientBanner convenientBanner;

    private ListBean item;

    private Gson gson = new Gson();

    private ImageView userImageView,userCommentImageView;

    private TextView nameTextView,
            locationAndPostTimeTextView,
            titleTextView,
            priceTextView,
            viewCountAndLikeCountTextView5,
            desc,
            collection_tv,
            comment_tv,
            superLike;

    private EditText comment_edt_content;

    private ExpandableListView mListView;

    private View send_comment, buttonView;

    private DetailListAdapter detailListAdapter;

    private SparseArray<List<ChildCommentsBean>> childMap = new SparseArray<>();

    private List<DetailListBean> groupList = new ArrayList<>();

//    private Unregistrar unregistrar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        toolbar2 = findViewById(R.id.toolbar2);
        toolbar2.inflateMenu(R.menu.detail_menu);
        toolbar2.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        Intent intent = getIntent();
        if (intent != null) {
            item = (ListBean) intent.getSerializableExtra("data");
        }

        if (item == null) return;

        onListViewInit();

        KeyboardUtils.fixAndroidBug5497(this);
        KeyboardUtils.registerSoftInputChangedListener(this,this);

    }


    private void onListViewInit() {
        mListView = findViewById(R.id.mListView);

        View header_view = LayoutInflater.from(this).inflate(R.layout.detail_header_view, mListView, false);

        mListView.addHeaderView(header_view);

        mListView.setGroupIndicator(null);

        DetailData data = gson.fromJson(DetailListData.JSON, DetailData.class);

        DataBean dataBean = data.getData();

        List<DetailListBean> list = dataBean.getList();

        groupList.addAll(list);

        for (int i = 0; i < list.size(); i++) {

            DetailListBean detailListBean = list.get(i);

            List<ChildCommentsBean> chlid_comments = detailListBean.getChlid_comments();

            if (chlid_comments != null) {
                childMap.put(i, chlid_comments);
            }
        }

        detailListAdapter = new DetailListAdapter(childMap, groupList, this);

        mListView.setAdapter(detailListAdapter);

        for (int i = 0; i < groupList.size(); i++) {
            mListView.expandGroup(i);
        }

        mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });

        onBannerInit();
    }

    private void onBannerInit() {

        convenientBanner = findViewById(R.id.convenientBanner);

        String images = item.getImages();
        images = images.replace("\\", "");
//        Log.d(TAG, "images====" + images);
        Type type = new TypeToken<List<ImagesBean>>() {
        }.getType();
        List<ImagesBean> imagels = gson.fromJson(images, type);

        convenientBanner.setPages(
                new CBViewHolderCreator() {
                    @Override
                    public UrlImageHolderView createHolder(View itemView) {
                        return new UrlImageHolderView(itemView);
                    }

                    @Override
                    public int getLayoutId() {
                        return R.layout.item_url_image;
                    }
                }, imagels)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});

        onHeaderViewOthersViews();

    }

    private void onHeaderViewOthersViews() {
        userImageView = findViewById(R.id.userImageView);
        UserBean user = item.getUser();
        String user_image_url = getResources().getString(R.string.img_url_base);
        user_image_url = user_image_url + user.getImgpath();
        GlideApp.with(this)
                .load(user_image_url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_default_image)
                .centerCrop()
                .into(userImageView);

        nameTextView = findViewById(R.id.nameTextView);
        nameTextView.setText(user.getName());

        locationAndPostTimeTextView = findViewById(R.id.locationAndPostTimeTextView);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            Date parse = sdf.parse(item.getPost_time());
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
            locationAndPostTimeTextView.setText(format1.format(parse) + " " + item.getLocation());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        titleTextView = findViewById(R.id.titleTextView);
        titleTextView.setText(item.getTitle());

        priceTextView = findViewById(R.id.priceTextView);
        priceTextView.setText("¥" + item.getPrice());

        viewCountAndLikeCountTextView5 = findViewById(R.id.viewCountAndLikeCountTextView5);
        StatisticalBean statistical = item.getStatistical();
        String string = "浏览 " + statistical.getView_count() + "  " + "点赞 " + statistical.getLike_count();
        viewCountAndLikeCountTextView5.setText(string);

        desc = findViewById(R.id.desc);
        desc.setText(item.getDesc());

        collection_tv = findViewById(R.id.collection_tv);
        comment_tv = findViewById(R.id.comment_tv);
        superLike = findViewById(R.id.superLike);
        send_comment = findViewById(R.id.send_comment);
        buttonView = findViewById(R.id.buttonView);
        comment_edt_content = findViewById(R.id.comment_edt_content);
        userCommentImageView = findViewById(R.id.userCommentImageView);
        GlideApp.with(this)
                .load(user_image_url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_default_image)
                .centerCrop()
                .into(userCommentImageView);



        collection_tv.setOnClickListener(this);

        comment_tv.setOnClickListener(this);
        superLike.setOnClickListener(this);
    }

    // 开始自动翻页
    @Override
    protected void onResume() {
        super.onResume();
//        //开始自动翻页
        convenientBanner.startTurning();
    }

    // 停止自动翻页
    @Override
    protected void onPause() {
        super.onPause();
//        //停止翻页
        convenientBanner.stopTurning();
    }

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(this);
        super.onDestroy();
//        unregistrar.unregister();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.superLike:
                v.setSelected(!v.isSelected());
                break;
            case R.id.comment_tv:
                KeyboardUtils.showSoftInput(this);

                break;
            case R.id.collection_tv:
                v.setSelected(!v.isSelected());
                break;
         }
    }



    @Override
    public void onSoftInputChanged(int height) {
        if (KeyboardUtils.isSoftInputVisible(this)){
            send_comment.setVisibility(View.VISIBLE);
            buttonView.setVisibility(View.GONE);

            comment_edt_content.setFocusable(true);
            comment_edt_content.setFocusableInTouchMode(true);

            comment_edt_content.requestFocus();

        }else {
            send_comment.setVisibility(View.GONE);
            buttonView.setVisibility(View.VISIBLE);
            comment_edt_content.clearFocus();
//            KeyboardUtils.hideSoftInput(this);
        }
    }
}
